﻿using EFCore.BulkExtensions;
using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using iWare.Wms.Core;
using iWare.Wms.Core.Entity.Receiving;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System.Linq.Dynamic.Core;
using Yitter.IdGenerator;

namespace iWare.Wms.Application
{
    /// <summary>
    /// 送货单服务
    /// </summary>
    [Route("api/GoodsDelivery")]
    [ApiDescriptionSettings("供应商模块", Name = "GoodsDelivery", Order = 102)]

    public class GoodsDeliveryService : IDynamicApiController, ITransient
    {
        private readonly ILogger<GoodsDeliveryService> _logger;
        private readonly ISqlRepository<ERPDbContextLocator> _erpRep;
        private readonly IRepository<WareDictData, MasterDbContextLocator> _wareDictDataRep; //仓库字典值仓储
        private readonly IRepository<WareMaterial, MasterDbContextLocator> _wareMaterialRep; //物料仓储
        private readonly IRepository<PurchaseOrder, MasterDbContextLocator> _purchaseOrderRep; //采购订单仓储
        private readonly IRepository<GoodsDelivery, MasterDbContextLocator> _goodsDeliveryRep; //送货单仓储
        private readonly IRepository<GoodsDeliveryDetails, MasterDbContextLocator> _goodsDeliveryDetailsRep; //送货单明细仓储
        private readonly IRepository<GoodsDeliveryTagPrint, MasterDbContextLocator> _goodsDeliveryTagPrintRep; //送货单标签打印仓储
        private readonly IRepository<PurchaseOrderVsGoodsDelivery, MasterDbContextLocator> _purchaseOrderVsGoodsDeliveryRep; //采购订单与送货单关系仓储

        #region 默认
        /// <summary>
        /// 默认
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="erpRep"></param>
        /// <param name="wareDictDataRep"></param>
        /// <param name="wareMaterialRep"></param>
        /// <param name="purchaseOrderRep"></param>
        /// <param name="goodsDeliveryRep"></param>
        /// <param name="goodsDeliveryDetailsRep"></param>
        /// <param name="goodsDeliveryTagPrintRep"></param>
        /// <param name="purchaseOrderVsGoodsDeliveryRep"></param>
        public GoodsDeliveryService(
            ILogger<GoodsDeliveryService> logger,
            ISqlRepository<ERPDbContextLocator> erpRep,
            IRepository<WareDictData, MasterDbContextLocator> wareDictDataRep,
            IRepository<WareMaterial, MasterDbContextLocator> wareMaterialRep,
            IRepository<PurchaseOrder, MasterDbContextLocator> purchaseOrderRep,
            IRepository<GoodsDelivery, MasterDbContextLocator> goodsDeliveryRep,
            IRepository<GoodsDeliveryDetails, MasterDbContextLocator> goodsDeliveryDetailsRep,
            IRepository<GoodsDeliveryTagPrint, MasterDbContextLocator> goodsDeliveryTagPrintRep,
            IRepository<PurchaseOrderVsGoodsDelivery, MasterDbContextLocator> purchaseOrderVsGoodsDeliveryRep
        )
        {
            _logger = logger;
            _erpRep = erpRep;
            _wareDictDataRep = wareDictDataRep;
            _wareMaterialRep = wareMaterialRep;
            _purchaseOrderRep = purchaseOrderRep;
            _goodsDeliveryRep = goodsDeliveryRep;
            _goodsDeliveryDetailsRep = goodsDeliveryDetailsRep;
            _goodsDeliveryTagPrintRep = goodsDeliveryTagPrintRep;
            _purchaseOrderVsGoodsDeliveryRep = purchaseOrderVsGoodsDeliveryRep;
        }
        #endregion

        /// <summary>
        /// 分页查询供应商送货单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("Page")]
        public async Task<PageResult<GoodsDeliveryOutput>> Page([FromQuery] GoodsDeliverySearch input)
        {
            var userId = CurrentUserInfo.UserId;

            var goodsDeliverys = await _goodsDeliveryRep.DetachedEntities
                .Where(u => u.CreatedUserId == userId)
                .Where(input.Status != null && input.Status != AuditStatusEnum.all, u => u.Status == input.Status)
                .Where(input.IsJiaJiJian != null && input.IsJiaJiJian != YesOrNot.All, u => u.IsJiaJiJian == input.IsJiaJiJian)
                .Where(!string.IsNullOrEmpty(input.ProjectCode), u => EF.Functions.Like(u.ProjectCode, $"%{input.ProjectCode.Trim()}%"))
                .Where(!string.IsNullOrEmpty(input.DeliveryNo), u => EF.Functions.Like(u.DeliveryNo, $"%{input.DeliveryNo.Trim()}%"))
                .Where(!string.IsNullOrEmpty(input.PurchaseNo), u => EF.Functions.Like(u.PurchaseNo, $"%{input.PurchaseNo.Trim()}%"))
                .Where(!string.IsNullOrEmpty(input.SearchBeginTime), u => u.CreatedTime >= DateTime.Parse(input.SearchBeginTime.Trim()) &&
                 u.CreatedTime <= DateTime.Parse(input.SearchEndTime.Trim()))
                //.OrderByDescending(z => z.DeliveryType == "UrgentItem")
                .OrderBy(z => z.Status)
                .ThenByDescending(z => z.CreatedTime)
                .ProjectToType<GoodsDeliveryOutput>()
                .ToADPagedListAsync(input.PageNo, input.PageSize);

            foreach (var item in goodsDeliverys.Rows)
            {
                var purchaseOrder = await _purchaseOrderRep.FirstOrDefaultAsync(t => t.PurchaseNo == item.PurchaseNo && t.PurchaseType == item.DeliveryType);
                item.PurchaseId = purchaseOrder != null ? purchaseOrder.Id : 0;
                item.PurchaseNo = purchaseOrder != null && purchaseOrder.IsJiaJiJian == YesOrNot.Y ? "" : item.PurchaseNo;
                item.PurchaseTypeName = (await _wareDictDataRep.DetachedEntities
                    .Where(z => z.TypeId == 313570112090181 && z.Code == item.DeliveryType).FirstOrDefaultAsync()).Value;
            }

            return goodsDeliverys;
        }

        /// <summary>
        /// 获取创建送货单列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("CreateGoodsDeliveryList")]
        public async Task<PageResult<PurtdDetailsOutput>> CreateGoodsDeliveryList([FromQuery] PurchaseOrderDetailsInput input)
        {
            //获取当前送货单的下的明细
            var currGoodDeliveryModel = await _goodsDeliveryRep.DetachedEntities
                .Where(p => p.DeliveryNo == input.DeliveryNo)
                .ProjectToType<GoodsDelivery>().FirstOrDefaultAsync();

            //获取采购单下排除当前送货单号下所有的送货单明细集合
            var othergoodsDeliveryIdItem = await _purchaseOrderVsGoodsDeliveryRep.DetachedEntities
                .Where(p => p.PurchaseOrderId == input.PurchaseID)
                .Where(currGoodDeliveryModel != null, p => p.GoodsDeliveryId != currGoodDeliveryModel.Id)
                .Select(n => n.GoodsDeliveryId).ToListAsync();

            var othergoodDeliveryDetailList = await _goodsDeliveryDetailsRep.DetachedEntities
                .Where(othergoodsDeliveryIdItem != null, p => othergoodsDeliveryIdItem.Contains(p.GoodsDeliveryId))
                .ToListAsync();

            //根据ERP查询
            var purchaseModel = await _purchaseOrderRep.DetachedEntities.SingleOrDefaultAsync(p => p.Id == input.PurchaseID);
            var pURTCSearch = new PURTCSearch()
            {
                TC002 = purchaseModel.PurchaseNo,
                TC001 = purchaseModel.PurchaseType
            };

            //先查询ERP采购单身数据
            var pURTDOutputsList = await RedPURTD(input, pURTCSearch.TC002, pURTCSearch.TC001);
            if (pURTDOutputsList.TotalRows > 0)
            {
                foreach (var item in pURTDOutputsList.Rows)
                {
                    var sumcount = othergoodDeliveryDetailList
                        .Where(u => u.Code == item.Code.Trim() && u.Name == item.Name.Trim() && u.SpecificationModel == item.SpecificationModel.Trim())
                        .Select(t => t.DeliveryQuantity).Sum();
                    if (sumcount >= item.PurchaseNumber) continue;

                    var deliveryQuantity = item.PurchaseNumber - sumcount;

                    //判断当前的送货单下是否包含该物料的信息
                    if (currGoodDeliveryModel != null && currGoodDeliveryModel.GoodsDeliveryDetails != null)
                    {
                        var goodsDeliveryDetails = currGoodDeliveryModel.GoodsDeliveryDetails
                            .FirstOrDefault(p => p.Code == item.Code.Trim() && p.Name == item.Name.Trim() && p.SpecificationModel == item.SpecificationModel.Trim());
                        if (goodsDeliveryDetails != null)
                        {
                            item.IsCheck = true;
                            deliveryQuantity = goodsDeliveryDetails.DeliveryQuantity;
                        }
                    }

                    //获取物料的检验方式
                    //var InspectionMethod = InspectionMethodEnum.mianjian;
                    //var wareMateriaModel = await _wareMaterialRep.FirstOrDefaultAsync(n => n.Code == item.Code.Trim());
                    //if (wareMateriaModel != null) InspectionMethod = wareMateriaModel.InspectionMethod;

                    //获取物料的检验方式
                    var wareMateriaModel = await SelectMaterial(item.Code, item.SpecificationModel);

                    //是否结束
                    string isEnd = string.Empty;
                    if (item.IsEnd == "N") isEnd = "未结束";
                    else if (item.IsEnd == "Y") isEnd = "结束";
                    else isEnd = "指定结束";

                    // 查询品牌名称
                    var wareMaterial = await _wareMaterialRep.FirstOrDefaultAsync(z => z.Code == item.Code.Trim()
                        && z.Name == item.Name.Trim() && z.SpecificationModel == item.SpecificationModel.Trim());

                    item.PurchaseType = item.PurchaseType.Trim();
                    item.PurchaseNo = item.PurchaseNo.Trim();
                    item.ProjectCode = item.ProjectCode.Trim();
                    item.Code = item.Code.Trim();
                    item.Name = item.Name.Trim();
                    item.XuHao = item.XuHao.PadLeft(4, '0');
                    item.SpecificationModel = item.SpecificationModel.Trim();
                    item.Unit = item.Unit.Trim();
                    item.InspectionMethod = wareMateriaModel.InspectionMethod;
                    item.OutdeliveryQuantity = sumcount;
                    item.DeliveryQuantity = deliveryQuantity;
                    item.NotPurchaseNumber = item.PurchaseNumber - (sumcount + deliveryQuantity);
                    item.BrandName = wareMaterial == null || wareMaterial.BrandName == "无" ? "" : wareMaterial.BrandName;
                };

                return pURTDOutputsList;
            }
            else //没有则再查询送货单明细
            {
                //创建需要映射的送货单明细集合
                List<PurtdDetailsOutput> purchaseOrderDetailsList = new();

                var goodsDeliveryDetails = currGoodDeliveryModel.GoodsDeliveryDetails;
                foreach (var item in goodsDeliveryDetails)
                {
                    var itemmodel = item.Adapt<PurtdDetailsOutput>();
                    itemmodel.PurchaseNumber = purchaseModel.PurchaseNumber;
                    itemmodel.OutdeliveryQuantity = item.DeliveryQuantity;
                    itemmodel.NotPurchaseNumber = purchaseModel.PurchaseNumber - (item.DeliveryQuantity);
                    purchaseOrderDetailsList.Add(itemmodel);
                }

                return purchaseOrderDetailsList.ToADPagedList(input.PageNo, input.PageSize);
            }
        }

        /// <summary>
        /// 获取创建加急件送货单列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("CreateJiaJiJianList")]
        public async Task<PageResult<GoodsDeliveryDetailsOutput>> CreateJiaJiJianList([FromQuery] PurchaseOrderDetailsInput input)
        {
            //创建需要映射的送货单明细集合
            List<GoodsDeliveryDetailsOutput> purchaseOrderDetailsList = new();

            //获取当前送货单的下的明细
            var currGoodDeliveryModel = await _goodsDeliveryRep.DetachedEntities.Where(p => p.DeliveryNo == input.DeliveryNo)
                .ProjectToType<GoodsDelivery>().FirstOrDefaultAsync();

            //查询采购单
            var purchaseModel = await _purchaseOrderRep.DetachedEntities
                .SingleOrDefaultAsync(p => p.Id == input.PurchaseID);

            var goodsDeliveryDetails = currGoodDeliveryModel.GoodsDeliveryDetails;

            var xuHao = 0; //定义序号
            foreach (var item in goodsDeliveryDetails)
            {
                xuHao = xuHao + 1;

                var itemModel = item.Adapt<GoodsDeliveryDetailsOutput>();
                itemModel.XuHao = xuHao.ToString("0000");
                itemModel.PurchaseNumber = item.DeliveryQuantity;//purchaseModel.PurchaseNumber;
                itemModel.OutdeliveryQuantity = itemModel.PurchaseNumber - item.DeliveryQuantity;
                itemModel.NotPurchaseNumber = itemModel.PurchaseNumber - item.DeliveryQuantity;//purchaseModel.PurchaseNumber - (item.DeliveryQuantity);
                itemModel.IsEnd = "N";
                itemModel.IsCheck = true;
                purchaseOrderDetailsList.Add(itemModel);
            }

            return purchaseOrderDetailsList.ToADPagedList(input.PageNo, input.PageSize);
        }

        /// <summary>
        /// 编辑送货单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("AddGoodsDelivery")]
        //[UnitOfWork]
        public async Task AddGoodsDelivery(AddGoodsDeliveryInput input)
        {
            var goodsDeliveryModel = await _goodsDeliveryRep.DetachedEntities
                .Where(p => p.DeliveryNo == input.DeliveryNo)
                .ProjectToType<GoodsDelivery>().FirstOrDefaultAsync();
            if (goodsDeliveryModel == null) throw Oops.Oh("该采购单下无送货单明细!");

            //更新送货单总数量
            var updategoodsDeliveryModel = input.Adapt<GoodsDelivery>();
            //updategoodsDeliveryModel.DeliveryNo = YitIdHelper.NextId().ToString();  // 这里不需要创建新的送货单号。
            updategoodsDeliveryModel.DeliveryQuantityTotal = input.GoodsDeliveryDetailsInputList
                .Sum(t => t.DeliveryQuantity);
            updategoodsDeliveryModel.Id = goodsDeliveryModel.Id;
            await _goodsDeliveryRep.UpdateAsync(updategoodsDeliveryModel, true);
            _logger.LogInformation($"[GoodsDeliveryService-AddGoodsDelivery]送货单号:{updategoodsDeliveryModel.DeliveryNo},更新送货单总数量:{input.GoodsDeliveryDetailsInputList.Sum(t => t.DeliveryQuantity)}");

            //批量删除 通过 Nuget 安装 EFCore.BulkExtensions 包即可。
            if (goodsDeliveryModel.GoodsDeliveryDetails != null && goodsDeliveryModel.GoodsDeliveryDetails.Count > 0)
                await _goodsDeliveryDetailsRep.Context.BulkDeleteAsync(goodsDeliveryModel.GoodsDeliveryDetails);

            //批量删除送货标签打印记录表中的数据
            var deleteGoodsDeliveryTagPrintList = await _goodsDeliveryTagPrintRep
                .Where(p => p.GoodsDeliveryId == goodsDeliveryModel.Id).ToListAsync();
            if (deleteGoodsDeliveryTagPrintList != null && deleteGoodsDeliveryTagPrintList.Count > 0)
                await _goodsDeliveryTagPrintRep.Context.BulkDeleteAsync(deleteGoodsDeliveryTagPrintList);

            //批量新增送货详情信息
            List<GoodsDeliveryDetails> goodsDeliveryDetailList = new();
            //批量新增送货标签打印记录信息
            List<GoodsDeliveryTagPrint> goodsDeliveryTagPrintList = new List<GoodsDeliveryTagPrint>();

            _logger.LogInformation($"[GoodsDeliveryService-AddGoodsDelivery]前端接收-送货单号:{goodsDeliveryModel.DeliveryNo},创建送货单明细总数:{input.GoodsDeliveryDetailsInputList.Count()};详情:" + input.GoodsDeliveryDetailsInputList.ToJson());

            foreach (var item in input.GoodsDeliveryDetailsInputList)
            {
                item.GoodsDeliveryId = goodsDeliveryModel.Id;
                var goodsDeliveryDetails = item.Adapt<GoodsDeliveryDetails>();
                goodsDeliveryDetails.Id = YitIdHelper.NextId();
                goodsDeliveryDetails.GoodsDeliveryId = goodsDeliveryModel.Id;
                goodsDeliveryDetails.SupplierInfoCode = goodsDeliveryModel.SuppCode.Trim();
                goodsDeliveryDetails.CreatedUserId = CurrentUserInfo.UserId;
                goodsDeliveryDetails.CreatedUserName = CurrentUserInfo.Name;
                goodsDeliveryDetails.CreatedTime = DateTimeOffset.Now;
                goodsDeliveryDetails.BrandName = await _wareMaterialRep
                    .Where(z => z.Code == item.Code && z.SpecificationModel == item.SpecificationModel)
                    .Select(z => z.BrandName).FirstOrDefaultAsync();
                goodsDeliveryDetailList.Add(goodsDeliveryDetails);

                var wareMaterialTagModel = item.Adapt<GoodsDeliveryTagPrint>();
                var goodsDeliveryTagPrintModel = item.Adapt<GoodsDeliveryTagPrint>();
                wareMaterialTagModel.GoodsDeliveryId = goodsDeliveryModel.Id;
                wareMaterialTagModel.DeliveryNo = goodsDeliveryModel.DeliveryNo;
                wareMaterialTagModel.SupplierInfoCode = goodsDeliveryModel.SuppCode;
                wareMaterialTagModel.Quantity = item.DeliveryQuantity;
                wareMaterialTagModel.BrandName = await _wareMaterialRep.Where(z => z.Code == item.Code && z.SpecificationModel == item.SpecificationModel)
                    .Select(z => z.BrandName).FirstOrDefaultAsync();
                wareMaterialTagModel.CreatedTime = DateTime.Now;
                wareMaterialTagModel.CreatedUserId = CurrentUserInfo.UserId;
                wareMaterialTagModel.CreatedUserName = CurrentUserInfo.Name;
                wareMaterialTagModel.CreatedTime = DateTimeOffset.Now;
                goodsDeliveryTagPrintList.Add(wareMaterialTagModel);
            }

            //批量新增 通过 Nuget 安装 EFCore.BulkExtensions 包即可。
            await _goodsDeliveryDetailsRep.Context.BulkInsertAsync(goodsDeliveryDetailList);
            await _goodsDeliveryTagPrintRep.Context.BulkInsertAsync(goodsDeliveryTagPrintList);

            _logger.LogInformation($"[GoodsDeliveryService-AddGoodsDelivery]后端提交-送货单号:{goodsDeliveryModel.DeliveryNo},编辑送货单明细总数:{goodsDeliveryDetailList.Count()};详情:" + goodsDeliveryDetailList.ToJson());
            _logger.LogInformation($"[GoodsDeliveryService-AddGoodsDelivery]送货单号:{goodsDeliveryModel.DeliveryNo},编辑送货单标签打印总数:{goodsDeliveryTagPrintList.Count()};详情:" + goodsDeliveryTagPrintList.ToJson());
        }

        /// <summary>
        /// 删除送货单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("Delete")]
        //[UnitOfWork]
        public async Task Delete(DeleteGoodsDeliveryInput input)
        {
            // 查询送货单号信息
            var goodsDelivery = await _goodsDeliveryRep.DetachedEntities.Where(u => u.Id == input.Id).ProjectToType<GoodsDelivery>().FirstOrDefaultAsync();
            if (goodsDelivery == null) throw Oops.Oh("送货单信息不存在!");

            // 查询采购单信息
            var purchaseOrder = await _purchaseOrderRep.FirstOrDefaultAsync(z => z.PurchaseNo == goodsDelivery.PurchaseNo && z.PurchaseType == goodsDelivery.DeliveryType
            && z.SupplierInfoCode == CurrentUserInfo.Account);
            if (purchaseOrder == null) throw Oops.Oh("采购单信息不存在!");

            // 软删除采购单与送货单关系
            var purchaseOrderVsGoodsDelivery = await _purchaseOrderVsGoodsDeliveryRep.FirstOrDefaultAsync(z => z.PurchaseOrderId == purchaseOrder.Id && z.GoodsDeliveryId == goodsDelivery.Id);
            await _purchaseOrderVsGoodsDeliveryRep.FakeDeleteAsync(purchaseOrderVsGoodsDelivery);

            // 软删除送货单主表
            //await _goodsDeliveryRep.DeleteNowAsync(goodsDelivery);
            await _goodsDeliveryRep.FakeDeleteAsync(goodsDelivery);
            _logger.LogInformation($"[GoodsDeliveryService-Delete]软删除送货单:{goodsDelivery.DeliveryNo},操作人:{CurrentUserInfo.Account}");

            // 软删除送货单明细
            //var goodsDeliveryDetails = await _goodsDeliveryDetailsRep.DetachedEntities.Where(z => z.GoodsDeliveryId == goodsDelivery.Id).ToListAsync();
            foreach (var item in goodsDelivery.GoodsDeliveryDetails)
            {
                await _goodsDeliveryDetailsRep.FakeDeleteAsync(item);
            }

            // 批量删除送货标签打印记录表中的数据
            var deleteGoodsDeliveryTagPrintList = await _goodsDeliveryTagPrintRep.Where(p => p.DeliveryNo == goodsDelivery.DeliveryNo).ToListAsync();
            if (deleteGoodsDeliveryTagPrintList != null && deleteGoodsDeliveryTagPrintList.Count > 0)
            //await _goodsDeliveryTagPrintRep.Context.BulkDeleteAsync(deleteGoodsDeliveryTagPrintList);
            {
                foreach (var item in deleteGoodsDeliveryTagPrintList)
                {
                    // 这里改成软删除
                    await _goodsDeliveryTagPrintRep.FakeDeleteAsync(item);
                }
            }

            // 更新采购单状态
            if (purchaseOrder.IsJiaJiJian == YesOrNot.Y) purchaseOrder.Status = PurchaseStatusEnum.Delete;
            else purchaseOrder.Status = PurchaseStatusEnum.NotProgress;
            await _purchaseOrderRep.UpdateAsync(purchaseOrder);

            if (purchaseOrder.IsJiaJiJian == YesOrNot.Y)
                _logger.LogInformation($"[GoodsDeliveryService-Delete]采购单号:{purchaseOrder.PurchaseNo},更新采购单状态:{PurchaseStatusEnum.Delete},操作人:{CurrentUserInfo.Account}");
            else _logger.LogInformation($"[GoodsDeliveryService-Delete]采购单号:{purchaseOrder.PurchaseNo},更新采购单状态:{PurchaseStatusEnum.NotProgress},操作人:{CurrentUserInfo.Account}");
        }

        /// <summary>
        /// 采购单身-Les采购明细表
        /// </summary>
        [NonAction]
        public async Task<PageResult<PurtdDetailsOutput>> RedPURTD(PurchaseOrderDetailsInput input, string purchaseNo, string purchaseType)
        {
            if (string.IsNullOrEmpty(purchaseNo)) throw Oops.Oh(ErrorCode.D1011);
            string sql = string.Format($@"select row_number() over(order by pur.CREATE_DATE) as XuHao,
                                                 TD001 as PurchaseNo, --采购单别
	                                             TD002 as PurchaseType, --采购单号
	                                             TD004 as Code, --品号
	                                             TD005 as Name, --品名
	                                             TD006 as SpecificationModel, --规格
	                                             TD009 as Unit, --单位
	                                             --TD014, --备注
	                                             TD022 as ProjectCode, --项目编号
	                                             --UDF03, --参数
                                                 TD016 as IsEnd, --N:未结束、Y:自动结束、y:指定结束
                                                 --TD018  --审核码
						                         SUM(TD008) as PurchaseNumber
                                         from PURTD pur where TD018='Y' and TD002='{purchaseNo}' and TD001='{purchaseType}'
                                         group by TD001,TD002,TD004,TD005,TD006,TD009,TD016,TD022,CREATE_DATE");
            var purtdList = await _erpRep
              .SqlQueryAsync<PurtdDetailsOutput>(sql);

            int startIndex = (input.PageNo - 1) * input.PageSize + 1;
            int endIndex = startIndex + input.PageSize - 1;

            //分页
            string pageSql = @"with
                                 tb as
                                 (
                                     " + sql + @"
                                 )  select * from tb where XuHao between " + startIndex + " and " + endIndex;

            var list = await _erpRep
                .SqlQueryAsync<PurtdDetailsOutput>(pageSql);

            return list.ToADPagedList20230214(purtdList, input.PageNo, input.PageSize);
        }

        /// <summary>
        /// 根据条件查询物料信息
        /// </summary>
        /// <returns></returns>
        [NonAction]
        public async Task<WareMaterial> SelectMaterial(string code, string specificationModel)
        {
            var materialList = await _erpRep
                .SqlQueryAsync<MaterialErpInput>
                 (@"select MB001, --品号
	                       MB002, --品名
	                       MB003, --规格
	                       MB004, --库存单位
	                       MB009, --商品描述
	                       MB043, --检验方式 0:免检、1:抽检(减量)、2:抽检(正常)、3:抽检(加严)、4:全检
                           MB064, --库存数量
                           UDF07  --品牌名称
                    from INVMB where MB001='" + code + "' and MB003='" + specificationModel + "'");

            var materialErpInputModel = materialList.FirstOrDefault();

            //抽检方式
            var inspectionMethod = InspectionMethodEnum.mianjian;
            if (materialErpInputModel.MB043.Equals(0))
                inspectionMethod = InspectionMethodEnum.mianjian;
            else if (materialErpInputModel.MB043.Equals(1))
                inspectionMethod = InspectionMethodEnum.choujian_jianliang;
            else if (materialErpInputModel.MB043.Equals(2))
                inspectionMethod = InspectionMethodEnum.choujian_zhengchang;
            else if (materialErpInputModel.MB043.Equals(3))
                inspectionMethod = InspectionMethodEnum.choujian_jiayan;
            else
                inspectionMethod = InspectionMethodEnum.quanjian;

            return new WareMaterial
            {
                Code = materialErpInputModel.MB001 == null ? "" : materialErpInputModel.MB001.Trim(),
                Name = materialErpInputModel.MB002 == null ? "" : materialErpInputModel.MB002.Trim(),
                SpecificationModel = materialErpInputModel.MB003 == null ? "" : materialErpInputModel.MB003.Trim(),
                Unit = materialErpInputModel.MB004 == null ? "" : materialErpInputModel.MB004.Trim(),
                Describe = materialErpInputModel.MB009 == null ? "" : materialErpInputModel.MB009.Trim(),
                InspectionMethod = inspectionMethod,
                Quantity = materialErpInputModel.MB064,
                BrandName = materialErpInputModel.UDF07,
                SupplerCode = "",
                IsJiaJi = YesOrNot.N,
                CreatedUserName = "LES SYSTEM",
                CreatedTime = DateTimeOffset.Now
            };
        }

        /// <summary>
        /// 测试数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("Test")]
        [NonAction]
        public async Task Test([FromQuery] TestAddGoodsDeliveryInput input)
        {
            var goodsDelivery = await _goodsDeliveryRep.FirstOrDefaultAsync(z => z.DeliveryNo == input.DeliveryNo);

            var wareMaterial = (await _wareMaterialRep.DetachedEntities
                .Where(z => z.InspectionMethod == input.InspectionMethod && z.BrandName != "无" && z.BrandName != "")
                .ToListAsync()).Take(15);

            foreach (var item in wareMaterial)
            {
                // 新增送货明细信息
                var details = new GoodsDeliveryDetails();
                details.GoodsDeliveryId = goodsDelivery.Id;
                details.Code = item.Code;
                details.Name = item.Name;
                details.SpecificationModel = item.SpecificationModel;
                details.InspectionMethod = item.InspectionMethod;
                details.Unit = item.Unit;
                details.DeliveryQuantity = new Random().Next(1, 100);
                details.BrandName = await _wareMaterialRep.DetachedEntities.Where(z => z.Code == item.Code && z.SpecificationModel == item.SpecificationModel)
                    .Select(z => z.BrandName).FirstOrDefaultAsync();
                details.XuHao = "";
                details.ProjectCode = goodsDelivery.ProjectCode;
                await _goodsDeliveryDetailsRep.InsertAsync(details);

                // 新增送货标签信息
                var wareMaterialTagModel = item.Adapt<GoodsDeliveryTagPrint>();
                var goodsDeliveryTagPrintModel = item.Adapt<GoodsDeliveryTagPrint>();
                wareMaterialTagModel.GoodsDeliveryId = goodsDelivery.Id;
                wareMaterialTagModel.DeliveryNo = goodsDelivery.DeliveryNo;
                wareMaterialTagModel.SupplierInfoCode = goodsDelivery.SuppCode.Trim();
                wareMaterialTagModel.Quantity = new Random().Next(1, 100);
                wareMaterialTagModel.BrandName = await _wareMaterialRep.Where(z => z.Code == item.Code && z.SpecificationModel == item.SpecificationModel)
                    .Select(z => z.BrandName).FirstOrDefaultAsync();
                await _goodsDeliveryTagPrintRep.InsertAsync(wareMaterialTagModel);
            }
        }
    }
}
